package com.example.demo.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis缓存调用的Java方法
 * @author chenlinyan
 * @date 2019/5/25 11:34
 * @description：RedisTemplate会自动装配
 * @version v2.0.0
 * @see {@link org.springframework.boot.autoconfigure.data.redis}
 */
@Slf4j
@Component
public class Redis2Service {

	/* @Autowired
	    @Qualifier("redisTemplate")
	    private RedisTemplate redisTemplate;*/
	private RedisTemplate redisTemplate;

	@Autowired(required = false)
	public void setRedisTemplate(RedisTemplate redisTemplate) {
	     RedisSerializer stringSerializer = new StringRedisSerializer();
	     redisTemplate.setKeySerializer(stringSerializer);
	     redisTemplate.setValueSerializer(stringSerializer);
	     redisTemplate.setHashKeySerializer(stringSerializer);
	     redisTemplate.setHashValueSerializer(stringSerializer);
	     this.redisTemplate = redisTemplate;
	}
    /**
     * 写入redis缓存
     * @param key 键
     * @param value value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }

    /**
     * 写入redis缓存,如果key存在，不进行操作
     * @param key 键
     * @param value value
     * @return
     */
    public boolean setnx(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.setIfAbsent(key, value);
            result = true;
        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }
    
    /**
     * 获取redis缓存
     * @param key 键
     * @return
     */
    
    
    
    public Object get(String key) {
    	  Object object = null;
        try {
        	object = redisTemplate.opsForValue().get(key);
             
        } catch (Exception e) {
            log.error("get key value error", e);
        }
        
        return object;
    }
    
    
    
    /**
     * 写入redis缓存
     * @param key 键
     * @param value value
     * @return
     */
    public boolean setTime(final String key, Object value,long timeout, TimeUnit unit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value,timeout,unit);
            result = true;
           
        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }

    /**
     * 写入redis缓存
     * @param key 键
     * @param value value
     * @return
     */
    public boolean setnxTime(final String key, Object value,long timeout, TimeUnit unit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.setIfAbsent(key, value,timeout,unit);
            result = true;

        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }

    /**
     * 删除指定key
     * @param key
     * @return
     */
    public boolean hasKey(Object key){
        return redisTemplate.hasKey(key);
    }
    
    /**
     * 删除指定key
     * @param key
     * @return
     */
    public void delete(Object key){
         redisTemplate.delete(key);
    }

    /*set开始*/

    /**
     * 写入redis缓存
     * @param key 键
     * @param value value
     * @return
     */
    public boolean add(final String key, Object... value) {
        boolean result = false;
        try {
            redisTemplate.opsForSet().add(key,value);
            result = true;
        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }

    /**
     * 获取redis缓存
     * @param key 键
     * @return  list集合
     */
    public List<String> sget(String key){
        Set members = redisTemplate.opsForSet().members(key);
        List<String> result = new ArrayList<>(members);
        return result;
    }

    /**
     * 写入redis缓存加过期时间
     * @param key 键
     * @param value value
     * @return
     */
    public boolean ssetTime(final String key, Object value,long timeout, TimeUnit unit) {
        boolean result = false;
        try {
            redisTemplate.opsForSet().add(key,value);
            redisTemplate.boundValueOps(key).expire(timeout,unit);
            result = true;

        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key  键
     * @param value 值
     * @return  boolean
     */
    public boolean shasKey(String key,Object value){
        return redisTemplate.boundSetOps(key).isMember(value);
    }

    /**
     * 获取Set缓存的长度
     * @param key
     * @return
     */
    public Long sgetSize(String key){
        return redisTemplate.boundSetOps(key).size();
    }

    /**
     * 移除指定的元素
     * @param key
     * @param value
     * @return
     */
    public Long sremove(String key,Object... value){
        return redisTemplate.boundSetOps(key).remove(value);
    }

    /*set结束*/

    /*Hash类型开始*/
    /**
     * 写入redis缓存
     * @param key 键
     * @param value value
     * @return
     */
    public boolean hput(final String key, String minKey, Object... value) {
        boolean result = false;
        try {
            redisTemplate.opsForSet().add(key,value);
            result = true;
        } catch (Exception e) {
            log.error("set key value error", e);
        }
        return result;
    }

    /*Hash类型结束*/


    /**
     * 使用scan命令 查询某些前缀的key 有多少个
     * 用来获取当前session数量,也就是在线用户
     * @param key
     * @return
     */
    public Long scanSize(String key){
        long dbSize = (long) this.redisTemplate.execute(new RedisCallback<Long>() {

            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                long count = 0L;
                Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(key).count(1000).build());
                while (cursor.hasNext()) {
                    cursor.next();
                    count++;
                }
                return count;
            }
        });
        return dbSize;
    }

}